﻿using Ebusiness_Authservice.Entities;
using Ebusiness_Authservice.Services.Dtos;
using Ebusiness_OrderService.Repositorys;
using Microsoft.AspNetCore.Authentication;
using Microsoft.AspNetCore.Authentication.Cookies;


//using Microsoft.AspNetCore.Identity.Data;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Caching.Memory;
using OpenIddict.Abstractions;
using OpenIddict.Server.AspNetCore;
using System.Security.Claims;
using Volo.Abp.AspNetCore.Mvc;
using Volo.Abp.Domain.Repositories;

namespace Ebusiness_Authservice.Controllers
{
    /// <summary>
    /// 认证控制器
    /// 处理用户注册、登录和令牌回收等认证相关操作
    /// </summary>
    [ApiController]
    [Route("[controller]")]
    public class AuthController : AbpController
    {
        public IOpenIddictApplicationManager _applicationManager { get; set; }
        public IOpenIddictScopeManager _scopeManager { get; set; }
        public IOpenIddictTokenManager _tokenManager { get; set; }
        public IAuthserRepository AuthserRepository { get; set; }
        public IMemoryCache _cache { get; set; }

        public AuthController()
        {

        }

        /// <summary>
        /// 用户注册页面
        /// </summary>
        /// <returns>注册页面视图</returns>
        [HttpGet("register")]
        public IActionResult Register()
        {
            return View();
        }

        /// <summary>
        /// 用户注册处理
        /// 创建新用户账户
        /// </summary>
        /// <param name="request">注册请求数据</param>
        /// <returns>注册结果</returns>
        [HttpPost("register")]
        public async Task<IActionResult> Register([FromForm] RegisterRequest request)
        {
            // 验证模型
            if (!ModelState.IsValid)
            {
                return View(request);
            }

            // 检查用户名是否已存在
            if (await AuthserRepository.FirstOrDefaultAsync(u => u.UserName == request.Username) != null)
            {
                ModelState.AddModelError("Username", "用户名已存在");
                return View(request);
            }

            // 检查邮箱是否已存在
            if (await AuthserRepository.FirstOrDefaultAsync(u => u.Email == request.Email) != null)
            {
                ModelState.AddModelError("Email", "邮箱地址已被注册");
                return View(request);
            }

            // 创建新用户对象
            var user = new ApplicationUser
            {
                UserName = request.Username,                                    // 设置用户名
                Email = request.Email,                                          // 设置邮箱
                PasswordHash = BCrypt.Net.BCrypt.HashPassword(request.Password), // 使用BCrypt加密密码
                Roles = new List<string> { "User" }                            // 设置默认角色为User
            };

            try
            {
                // 将用户添加到数据库
                await AuthserRepository.InsertAsync(user);

                // 注册成功，重定向到登录页面
                TempData["SuccessMessage"] = "注册成功！请登录您的账户。";
                return RedirectToAction("Login");
            }
            catch (Exception ex)
            {
                ModelState.AddModelError("", "注册失败，请稍后重试");
                return View(request);
            }
        }

        /// <summary>
        /// 用户登录页面
        /// </summary>
        /// <param name="returnUrl">登录成功后的返回地址</param>
        /// <returns>登录页面视图</returns>
        [HttpGet("login")]
        public IActionResult Login(string returnUrl = null)
        {
            if (returnUrl != null)
                HttpContext.Session.SetString("ReturnUrl", returnUrl);
            ViewBag.ReturnUrl = HttpContext.Session.GetString("ReturnUrl");
            return View();
        }

        /// <summary>
        /// 用户登录处理
        /// 验证用户凭据并创建认证票据
        /// </summary>
        /// <param name="request">登录请求数据</param>
        /// <param name="returnUrl">登录成功后的返回地址</param>
        /// <returns>登录结果</returns>
        [HttpPost("login")]
        public async Task<IActionResult> Login([FromForm] LoginRequest request, [FromForm] string returnUrl)
        {
            // 根据用户名查找用户
            var user = await AuthserRepository.FirstOrDefaultAsync(u => u.UserName == request.Username);

            // 验证用户存在且密码正确
            if (user == null || !BCrypt.Net.BCrypt.Verify(request.Password, user.PasswordHash))
            {
                ModelState.AddModelError("", "用户名或密码错误");
                ViewBag.ReturnUrl = returnUrl;
                return View(request);
            }

            // 创建用户声明（Claims）
            var claims = new List<Claim>
        {
            new Claim(ClaimTypes.NameIdentifier, user.Id.ToString()),           // 用户主体标识
            new Claim (ClaimTypes.Name, user.UserName),              // 用户名
            new Claim(ClaimTypes.Email, user.Email),                // 邮箱
            new Claim(ClaimTypes.Role, string.Join(",", user.Roles)) // 角色（多个角色用逗号分隔）
        };

            // 创建身份标识和主体
            var identity = new ClaimsIdentity(claims, CookieAuthenticationDefaults.AuthenticationScheme);
            var principal = new ClaimsPrincipal(identity);
            AuthenticationProperties authenticationProperties = new AuthenticationProperties();
            //设置过期时间
            authenticationProperties.IsPersistent = true;
            authenticationProperties.ExpiresUtc = DateTimeOffset.UtcNow.AddHours(6);
            // 使用Cookie进行身份认证
            //await HttpContext.SignInAsync("Cookies", principal);
            await HttpContext.SignInAsync(CookieAuthenticationDefaults.AuthenticationScheme, principal, authenticationProperties);

            // 检查是否有待处理的授权请求
            if (!string.IsNullOrEmpty(returnUrl) && returnUrl.Contains("auth_key="))
            {
                var authKey = returnUrl.Split("auth_key=").Last();
                if (_cache.TryGetValue(authKey, out AuthorizationRequest authRequest))
                {
                    // 清除缓存的授权请求
                    _cache.Remove(authKey);

                    // 重定向到授权端点，继续授权流程
                    var authUrl = $"/connect/authorize?client_id={authRequest.ClientId}&redirect_uri={authRequest.RedirectUri}&scope={authRequest.Scope}&state={authRequest.State}&response_type={authRequest.ResponseType}&nonce={authRequest.Nonce}";
                    return Redirect(authUrl);
                }
            }

            // 如果没有待处理的授权请求，重定向到默认页面
            if (!string.IsNullOrEmpty(returnUrl) && Url.IsLocalUrl(returnUrl))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }

        /// <summary>
        /// 用户退出登录
        /// </summary>
        /// <returns>重定向到首页</returns>
        [HttpPost("logout")]
        public async Task<IActionResult> Logout()
        {
            await HttpContext.SignOutAsync("Cookies");
            return RedirectToAction("Index", "Home");
        }
    }
}
